const { connection } = require("../base/connect");
const { throwError } = require("../base/error");
const { sendData } = require("../base/success");
module.exports = async (ctx) => {
  const collection = (await connection).collection("area");
  let result = new Object();
  // 获取用户输入的参数
  const province = ctx.query.province;
  if (!province) {
    result = await collection
      // 拿到各省所有地区数据,并排除掉没有用的属性
      .find({}, { projection: { _id: 0, type: 0 } })
      .toArray();
  } else {
    const temp = await collection
      .find({}, { projection: { _id: 0, type: 0 } })
      .toArray();
    // 通过遍历拿到与用户传入参数相同的地区数据
    for (let i = 0; i < temp.length; i++) {
      if (temp[i].properties.name.indexOf(province) != -1) {
        result = temp[i];
        break;
      }
    }
    // 没有拿到数据
    if (JSON.stringify(result) == "{}") {
      throwError(ctx, -1, "地区不存在~");
      return;
    }
  }
  sendData(ctx, result);
};
